//
//  LBXImageBrowserView.m
//  ImageBrowse
//
//  Created by bike on 17/2/4.
//  Copyright © 2017年 bike. All rights reserved.
//

#import "LBXImageBrowserView.h"

@interface LBXImageBrowserView () <UIScrollViewDelegate>

@end

@implementation LBXImageBrowserView

+ (instancetype)createImageBrowserViewWithFrame:(CGRect)frame
{
    LBXImageBrowserView *browserView = [[LBXImageBrowserView alloc] initWithFrame:frame];
    [browserView setupUI];
    return browserView;
}

- (void)setupUI
{
    _bgScrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
    _bgScrollView.delegate = self;
    _bgScrollView.bounces = YES;
    _bgScrollView.bouncesZoom = YES;
    _bgScrollView.minimumZoomScale = 1.0;
    _bgScrollView.maximumZoomScale = 2.0;
    _bgScrollView.showsVerticalScrollIndicator = NO;
    _bgScrollView.showsHorizontalScrollIndicator = NO;
    _bgScrollView.backgroundColor = [UIColor clearColor];
    [self addSubview:_bgScrollView];
    
    _imageView = [[UIImageView alloc] initWithFrame:_bgScrollView.bounds];
    _imageView.contentMode = UIViewContentModeScaleAspectFit;
    [_bgScrollView addSubview:_imageView];
}

#pragma Action

- (void)doubleTapAction:(UITapGestureRecognizer *)tap
{
    //双击放大或者缩小
    UIScrollView *scrollView = (UIScrollView *)tap.view;
    if (scrollView.zoomScale > 1) {
        [scrollView setZoomScale:1.0 animated:YES];
    }
    else {
        [scrollView setZoomScale:2.0 animated:YES];
    }
}

#pragma mark - UIScrollViewDelegate

- (nullable UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    //在图片还未超出屏幕的时候，scrollView的frame跟随图片的缩放而变化
    CGFloat viewHeight = CGRectGetHeight(self.bounds);
    CGFloat viewWidth = CGRectGetWidth(self.bounds);
    CGSize imageSize = _imageView.frame.size;
    CGFloat height = imageSize.height;
    CGFloat width = imageSize.width;
    if (height > viewHeight) {
        height = viewHeight;
    }
    if ( width > viewWidth) {
        width = viewWidth;
    }
    _bgScrollView.frame = CGRectMake((viewWidth - width) / 2.0, (viewHeight - height) / 2.0, width, height);
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
